import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import monitor from "../monitor.vue";
import { addDrawer } from "@/components/ReDrawer/index";
// import { getOnlineLogsList } from "@/apiOld/system";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import {
  outbound_list,
  task_Start_Pause,
  taskAdd,
  task_taskDel,
  task_taskInfo
} from "@/api/outbound";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole() {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_outboundTask_add: false, // 外呼任务添加

    is_search_name: false, // 搜索名称
    is_search_status: false, // 搜索状态

    is_single_watch: false, // 监控
    is_single_recycle: false, // 回收未接
    is_single_pause: false, // 暂停
    is_single_excute: false, // 开始
    is_single_delete: false, // 删除

    is_batch_delete: false, // 批量删除
    is_batch_recycle: false // 批量回收未接
  });

  // 列表
  const form = reactive({
    name: "",
    status: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns = reactive<TableColumnList>([
    {
      type: "selection",
      align: "left"
    },
    {
      label: "任务名称",
      prop: "name",
      minWidth: 200
    },
    {
      label: "外呼类型",
      // prop: "transferType",
      minWidth: 200,
      cellRenderer: ({ row, index }) => (
        <>
          {row.transferType == 1
            ? "技能组"
            : row.transferType == 2
              ? "ivr"
              : "机器人"}
        </>
      )
    },
    {
      label: "创建时间",
      prop: "cts",
      minWidth: 120
      // formatter: ({ time }) =>
      //   dayjs(loginTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "进度",
      prop: "progress",
      minWidth: 300,
      cellRenderer: ({ row }) => (
        <div class="progress">
          <p>
            {row.outCallCnt} / {row.contactCnt}
          </p>
          <div class="barInner">
            <div
              class="bar"
              style={"width: " + (row.outCallCnt / row.contactCnt) * 100 + "%"}
            ></div>
          </div>
        </div>
      )
    },
    {
      label: "执行状态",
      prop: "status",
      minWidth: 180,
      cellRenderer: ({ row, index }) => (
        <>
          {row.status == 0
            ? "删除"
            : row.status == 1
              ? "关闭"
              : row.status == 2
                ? "创建"
                : row.status == 3
                  ? "关联名单"
                  : row.status == 4
                    ? "拨打中"
                    : row.status == 5
                      ? "暂停"
                      : "完成"}
        </>
      )
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ]);

  const tableRef = ref();
  const multipleSelection = ref([]);

  function handleSizeChange(val: number) {
    pagination.pageCount = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    // multipleSelection.value = val;
    let arr = [];
    val.map(item => {
      if (item.status == 3 || item.status == 4) {
        // message(`进行中状态不可删除`);
      } else {
        arr.push({ status: item.status, task_id: item.id });
      }
    });
    multipleSelection.value = arr;
  }
  // 多选删除
  function changeDel() {
    ElMessageBox.confirm("确定执行该操作？", "重要提示", {
      type: "warning"
    })
      .then(() => {
        task_taskDel({
          taskData: multipleSelection.value
        }).then(res => {
          if (res.code == 1000) {
            onSearch();
          }
        });
      })
      .catch(() => {});
  }

  function handleSelectionClear() {
    const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
    clearSelection();
  }

  // 对数据操作
  function handleCommand(row, e) {
    // 判断是否选择的监控
    if (e == "monitor") {
      addDrawer({
        title: `实时监控`,
        props: {
          formInline: {
            name: row?.name || "",
            cruiseParam1: row?.cruiseParam1 || "",
            id: row?.id || ""
          }
        },
        lockScroll: true,
        size: "100%",
        hideFooter: true,
        style: { background: "#f0f2f5" },
        contentRenderer: () => h(monitor, { ref: formRef, formInline: null }),
        close: () => {
          //  getOutboundList();
        },
        closeCallBack: () => {
          onSearch();
        }
        // beforeSure: (done, { options }) => {
        //   done(); // 关闭弹框
        //   getOutboundList(); // 刷新表格数据
        // }
      });
    } else if (e == "pause") {
      // 暂停
      ElMessageBox.confirm("确定执行该操作？", "重要提示", {
        type: "warning"
      })
        .then(() => {
          task_Start_Pause({
            task_id: row?.id || "",
            status: 5
          }).then(res => {
            if (res.code == 1000) {
              onSearch();
            }
          });
        })
        .catch(() => {});
    } else if (e == "start") {
      // 开始
      ElMessageBox.confirm("确定执行该操作？", "重要提示", {
        type: "warning"
      })
        .then(() => {
          task_Start_Pause({
            task_id: row?.id || "",
            status: 4
          }).then(res => {
            if (res.code == 1000) {
              onSearch();
            }
          });
        })
        .catch(() => {});
    } else if (e == "delete") {
      // 删除
      ElMessageBox.confirm("确定执行该操作？", "重要提示", {
        type: "warning"
      })
        .then(() => {
          let obj = {
            status: row.status,
            task_id: row.id
          };
          task_taskDel({
            taskData: [obj]
          }).then(res => {
            if (res.code == 1000) {
              onSearch();
            }
          });
        })
        .catch(() => {});
    }
  }

  // 表单
  const formRef = ref();
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}外呼任务`,
      props: {
        formInline: {
          task_name: row?.task_name ?? ""
        }
      },
      width: "440px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了任务名称为${curData.task_name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              taskAdd(curData).then(res => {
                if (res.code == 1000) {
                  chores();
                }
              });
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    // const { data } = await getOnlineLogsList(toRaw(form));
    // dataList.value = data.list;
    // pagination.total = data.total;
    // pagination.pageSize = data.pageSize;
    // pagination.currentPage = data.currentPage;

    outbound_list({
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      status: form.status || "",
      _name: form.name || ""
    }).then(res => {
      if (res.code == 1000) {
        loading.value = false;
        pagination.total = res.data.total;
        dataList.value = res.data.list.map(i => ({
          ...i,
          cts: i.cts ? dayjs(i.cts * 1000).format("YYYY-MM-DD HH:mm:ss") : ""
        }));
      }
    });
  }
  // 查询详情更新列表
  setInterval(() => {
    dataList.value.map(item=>{
      if(item.status == 4) {
        task_taskInfo({ task_id : item.id }).then()
        onSearch()
      }
    })
  }, 60000);
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/groupcallManagement/task/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(
        ([key, value]) => value.onpage === "/groupcallManagement/task/index"
      );
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // outboundTask_add
      if (homeDataObj.outboundTask_add) permissions.is_outboundTask_add = true;
      // outboundTask_list
      if (homeDataObj.outboundTask_list) {
        // search
        if (
          homeDataObj.outboundTask_list.search &&
          homeDataObj.outboundTask_list.search.length
        ) {
          let permiss = homeDataObj.outboundTask_list.search.join(",");
          permissions.is_search_name = permiss.includes("name") ? true : false;
          permissions.is_search_status = permiss.includes("status")
            ? true
            : false;
        }
        // single
        if (
          homeDataObj.outboundTask_list.single &&
          homeDataObj.outboundTask_list.single.length
        ) {
          let permiss = homeDataObj.outboundTask_list.single.join(",");
          permissions.is_single_watch = permiss.includes("watch")
            ? true
            : false;
          permissions.is_single_recycle = permiss.includes("recycle")
            ? true
            : false;
          permissions.is_single_pause = permiss.includes("pause")
            ? true
            : false;
          permissions.is_single_excute = permiss.includes("excute")
            ? true
            : false;
          permissions.is_single_delete = permiss.includes("delete")
            ? true
            : false;
        }
        // batch
        if (
          homeDataObj.outboundTask_list.batch &&
          homeDataObj.outboundTask_list.batch.length
        ) {
          let permiss = homeDataObj.outboundTask_list.batch.join(",");
          permissions.is_batch_delete = permiss.includes("delete")
            ? true
            : false;
          permissions.is_batch_recycle = permiss.includes("recycle")
            ? true
            : false;
        }

        let tableRemove = homeDataObj.outboundTask_list.remove
          ? homeDataObj.outboundTask_list.remove.split(",")
          : [];
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1);
            }
          }
        }
      }
    }
  });

  return {
    permissions,

    form,
    loading,
    columns,
    dataList,
    pagination,
    tableRef,
    multipleSelection,
    onSearch,
    resetForm,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleSelectionClear,
    handleCommand,
    openDialog,
    changeDel
  };
}
